package cai.a.viewpager2;

import android.annotation.TargetApi;
import android.os.Build;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.PagerTitleStrip;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

/**
 * 实现步骤：
 *  一，布局中PagerTitleStrip被ViewPager包括
 *  二，PagerAdapter中多实现一个方法 getPageTitle()方法用于传递显示title
 */
public class MainActivity extends AppCompatActivity {

    private ViewPager mViewPager;
    private PagerTitleStrip mPagerTitleStrip;
    private List<View> mViewList;
    private String[] mTitle = {"title1", "title2", "title3", "title4"};

    private View view1;
    private View view2;
    private View view3;
    private View view4;

    @TargetApi(Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mViewPager = (ViewPager) findViewById(R.id.viewpager);
        mPagerTitleStrip = (PagerTitleStrip) findViewById(R.id.pagerTitleStrip);

        LayoutInflater ln = getLayoutInflater().from(MainActivity.this);
        mViewList = new ArrayList<View>();

        view1 = ln.inflate(R.layout.view1, null);
        view2 = ln.inflate(R.layout.view2, null);
        view3 = ln.inflate(R.layout.view3, null);
        view4 = ln.inflate(R.layout.view4, null);

        mViewList.add(view1);
        mViewList.add(view2);
        mViewList.add(view3);
        mViewList.add(view4);

        PagerAdapter pagerAdapter = new PagerAdapter() {
            /**ViewPager 显示数量*/
            @Override
            public int getCount() {
                return mViewList.size();
            }

            /**从ViewGroup中通过position移除指定View*/
            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView(mViewList.get(position));
            }

            /**将View添加到ViewGroup中*/
            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                container.addView(mViewList.get(position));
                return mViewList.get(position);
            }

            /**通过key验证，保证一一对应，这和上面添加View是对应的*/
            @Override
            public boolean isViewFromObject(View view, Object object) {
                return view == object;
            }

            /**获取显示的title*/
            @Override
            public CharSequence getPageTitle(int position) {
                return mTitle[position];
            }
        };

        mViewPager.setAdapter(pagerAdapter);
    }
}
